package cn.com.bluemoon.daps.standard.controller;


import cn.com.bluemoon.daps.common.datascope.BmPermission;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.standard.entity.DapStandardIndex;
import cn.com.bluemoon.daps.standard.entity.DapSystemCategory;
import cn.com.bluemoon.daps.standard.service.DapStandardIndexService;
import cn.com.bluemoon.daps.standard.service.DapSystemCategoryService;
import cn.com.bluemoon.daps.standard.vo.SystemCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.com.bluemoon.daps.common.constant.DapConstant.DapStandard.SYSTEM_TOPIC1_NAME;

/**
 * <p>
 * 基础标准&指标标准中用到的相关主题分类接口，非管理主题、分类接口
 * 管理接口{@link DapTopicDefineTopicCategoryController}
 * </p>
 *
 * @author admin
 * @since 2020-08-03
 */
@Api(tags = {"分类管理"})
@RestController
@Slf4j
@RequestMapping("/dapSystemCategory")
public class DapStandardTopicCategoryController {
    @Autowired
    private DapSystemCategoryService dapSystemCategoryService;

    @Autowired
    private DapStandardIndexService standardIndexService;

    @GetMapping("/topics/bizLineId")
    @ApiOperation(value = "根据业务线id获取层级主题列表数据")
    @BmPermission(value = "getDataTypeList", name = "根据业务线id获取层级主题列表数据", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<List<SystemCategoryVo>> topics(@RequestParam(value = "bizLineId") Integer bizLineId,
                                                      @RequestParam(value = "standardType", required = false, defaultValue = "1") Integer standardType) {
        Set<String> topicIds;
        if (standardType == 1) {
            LambdaQueryWrapper<DapStandardIndex> bizIndexes = standardIndexService.bmLambdaQuery().eq(DapStandardIndex::getBizLineId, bizLineId).select(DapStandardIndex::getBizLineId, DapStandardIndex::getTheme);
            List<DapStandardIndex> indexes = standardIndexService.list(bizIndexes);
            topicIds = indexes.stream().map(DapStandardIndex::getTheme).collect(Collectors.toSet());
        } else {
            throw new DapException("基础标准不支持业务线");
        }
        List<DapSystemCategory> topics = dapSystemCategoryService.findTopicsByLevel(0);
        List<SystemCategoryVo> res = topics.stream().filter(t -> topicIds.contains(t.getId()))
                .map(d -> {
                    SystemCategoryVo vo = new SystemCategoryVo();
                    BeanUtils.copyProperties(d, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        return ResultBean.ok(res);
    }


    @GetMapping("/topics/{level}")
    @ApiOperation(value = "获取层级主题列表数据")
    @BmPermission(value = "getDataTypeList", name = "获取层级主题列表数据", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<List<DapSystemCategory>> topics(@PathVariable(value = "level", required = false) Integer level) {
        // 默认去二级主题
        if (level == null) {
            level = 0;
        }
        List<DapSystemCategory> topics = dapSystemCategoryService.findTopicsByLevel(level);
        return ResultBean.ok(topics);
    }

    @GetMapping("/topicOrCategory/{type}")
    @BmPermission(value = "systemTopicAndCategories", name = "获取树形主题分类", ignore = true)
    @ApiOperation(value = "获取树形主题分类，type=1只获取主题数据 type=0 只获取分类数据，其他则获取主题和分类，")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<?> systemTopicAndCategories(@PathVariable String type) {
        return ResultBean.ok(dapSystemCategoryService.systemTopicAndCategories(type));
    }

    @GetMapping("/topicOrCategory/all")
    @BmPermission(value = "getTopicsAndCategoriesMap", name = "获取各主题和各分类的对象", ignore = true)
    @ApiOperation(value = "获取各主题和各分类的对象，{" + SYSTEM_TOPIC1_NAME + ": {}, topic2:{}, ...}")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<?> getTopicsAndCategoriesMap() {
        ImmutableMap<String, Map<String, List<DapSystemCategory>>> topicsAndCategories = dapSystemCategoryService.getTopicsAndCategories();
        return ResultBean.ok(topicsAndCategories);
    }

    @GetMapping("/categories/{parentId}/{level}")
    @ApiOperation(value = "根据主题id和层级分类获取分类列表数据")
    @BmPermission(value = "categories", name = "根据主题id和层级分类获取分类列表数据", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<List<DapSystemCategory>> categories(@PathVariable String parentId,
                                                          @PathVariable Integer level) {
        DapSystemCategory dapSystemCategory = new DapSystemCategory();
        dapSystemCategory.setTopic(0);
        dapSystemCategory.setParentId(parentId);
        if (level != null) {
            dapSystemCategory.setSubLevel(level);
        }
        List<DapSystemCategory> categories = dapSystemCategoryService.list(Wrappers.query(dapSystemCategory));
        return ResultBean.ok(categories);
    }

    @GetMapping("/categories/{parentId}")
    @ApiOperation(value = "根据主题id和层级分类获取分类列表数据-用于分类列表中")
    @BmPermission(value = "categories", name = "根据主题id和层级分类获取分类列表数据-用于分类列表中", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<Map<String, List<DapSystemCategory>>> categories(@PathVariable String parentId) {
        List<DapSystemCategory> systemCategories = dapSystemCategoryService.findSystemCategoriesByParentId(parentId);
        Map<String, List<DapSystemCategory>> map = Maps.newLinkedHashMap();
        SysCategoryGenerateHelper.buildSysCategories(map, systemCategories);
        return ResultBean.ok(map);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取分类信息")
    @BmPermission(value = "get", name = "获取分类信息", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapSystemCategory.class)})
    public ResultBean<DapSystemCategory> get(@ApiParam("分类id") @PathVariable("id") String id) {
        return ResultBean.ok(dapSystemCategoryService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除分类信息")
    @BmPermission(value = "del", name = "删除分类信息", ignore = true)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<Boolean> del(@ApiParam("id") @PathVariable("id") String id) {
        return ResultBean.ok(dapSystemCategoryService.deleteById(id, true));
    }

    /**
     * 构造返回分类数据
     */
    private final static class SysCategoryGenerateHelper {
        static final Map<Integer, String> CONVERT = new HashMap<Integer, String>() {{
            put(1, "一级分类");
            put(2, "二级分类");
            put(3, "三级分类");
        }};

        static void buildSysCategories(Map<String, List<DapSystemCategory>> map, List<DapSystemCategory> categories) {
            for (DapSystemCategory d : categories) {
                Integer l = d.getSubLevel();
                String key = CONVERT.get(l);
                if (map.get(key) == null) {
                    map.put(key, Lists.newArrayList(d));
                } else {
                    map.get(key).add(d);
                }
                if (d.getNextNodes() != null && !d.getNextNodes().isEmpty()) {
                    buildSysCategories(map, d.getNextNodes());
                }
            }
        }
    }


}
